/*
 * @Author: your name
 * @Date: 2021-05-19 14:08:10
 * @LastEditTime: 2021-05-19 18:32:43
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /xiangpan-admin/src/pages/login/tim.js
 */
import TIM from 'tim-js-sdk';
import LibGenerateTestUserSig from './lib-generate-test-usersig.min';

const SDKAPPID = 1400453671;

export const tim = TIM.create({
  SDKAppID: SDKAPPID,
});

export const timInit = async (userID, userSig) => {
  tim.setLogLevel(0); // 普通级别，日志量较多，接入时建议使用
  console.log('userSig==', userSig);

  TimLogin(userID, userSig);
};

function TimLogin(userID, userSig) {
  // const { userSig } = genTestUserSig(userID);

  let promise = tim.login({ userID: userID, userSig: userSig });
  promise
    .then(function (imResponse) {
      console.log(imResponse.data, 'imResponse===='); // 登录成功
      bindEvents();
      if (imResponse.data.repeatLogin === true) {
        // 标识账号已登录，本次登录操作为重复登录。v2.5.1 起支持
        console.log(imResponse.data.errorInfo);
      }
    })
    .catch(function (imError) {
      console.warn('login error==:', imError); // 登录失败的相关信息
    });
}

export const TimLogout = () => {
  let promise = tim.logout();
  promise
    .then(function (imResponse) {
      console.log(imResponse.data); // 登出成功
    })
    .catch(function (imError) {
      console.warn('logout error:', imError);
    });
};

const bindEvents = () => {
  tim.on(TIM.EVENT.SDK_READY, sendMessage);
  tim.on(TIM.EVENT.MESSAGE_RECEIVED, (event) => {
    console.log('event.data===', event.data);
  });

  //绑定tim的监听事件
  // tim.on(TIM.EVENT.SDK_READY, this.sdkReady); //sdkReady
  // tim.on(TIM.EVENT.KICKED_OUT, this.kickedOut); //有可能同名用户被踢出
  // tim.on(TIM.EVENT.ERROR, this.timError); //TIM内部出错
  // tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, this.conversation_list_updated); //会话列表更新
  // tim.on(TIM.EVENT.GROUP_LIST_UPDATED, this.group_list_updated); //群组列表更新
};

export const sendMessage = (toUserId) => {
  // 发送文本消息，Web 端与小程序端相同
  // 1. 创建消息实例，接口返回的实例可以上屏
  let message = tim.createTextMessage({
    to: toUserId,
    conversationType: TIM.TYPES.CONV_C2C,
    payload: {
      text: '发送消息',
    },
  });
  // 2. 发送消息
  let promise = tim.sendMessage(message);
  promise
    .then(function (imResponse) {
      // 发送成功
      console.log(imResponse, '发送成功==');
    })
    .catch(function (imError) {
      // 发送失败
      console.warn('sendMessage error发送失败:', imError);
    });
};
